#!/usr/bin/env python3
import zipfile
import xml.etree.ElementTree as ET
import re

DOCX_FILE = 'final-report.docx'

def get_document_xml(docx_path):
    with zipfile.ZipFile(docx_path) as docx:
        return docx.read('word/document.xml')

def get_paragraphs_with_styles(document_xml_bytes):
    ns = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
    root = ET.fromstring(document_xml_bytes)
    paragraphs = []
    for p in root.findall('.//w:p', ns):
        # 找段落样式
        pPr = p.find('w:pPr', ns)
        style = None
        if pPr is not None:
            pStyle = pPr.find('w:pStyle', ns)
            if pStyle is not None:
                style = pStyle.attrib.get('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val')

        # 拼接文本
        texts = []
        for t in p.findall('.//w:t', ns):
            texts.append(t.text)
        para_text = ''.join(texts) if texts else ''

        paragraphs.append((style, para_text))
    return paragraphs

def main():
    document_xml = get_document_xml(DOCX_FILE)
    paras = get_paragraphs_with_styles(document_xml)

    # 简单正则匹配章节编号，比如 1.2.3 或 2.1
    pattern = re.compile(r'^\d+(\.\d+)*\s+')

    print(f"{'样式ID':<15} | 段落内容")
    print('-' * 60)
    for style, text in paras:
        if not text.strip():
            continue
        mark = ''
        if pattern.match(text):
            mark = '<<章节编号>>'
        print(f"{style or 'None':<15} | {text} {mark}")

if __name__ == '__main__':
    main()
